package com.tmzn.service;

import cn.hutool.core.util.NumberUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.tmzn.db.DataSource;
import com.tmzn.db.DataSourceType;
import com.tmzn.domain.ImsShoppingGoods;
import com.tmzn.domain.TDevicePlan;
import com.tmzn.entity.param.BindParam;
import com.tmzn.jwt.JwtKit;
import com.tmzn.jwt.bean.MyIJwtAble;
import com.tmzn.mapper.TDeviceRecordMapper;
import com.tmzn.transdata.RpcResult;
import com.tmzn.util.SplitDataUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

@Service
public class DeviceService {

    @Autowired
    private IImsShoppingGoodsService iImsShoppingGoodsService;

    @Autowired
    private TDeviceRecordMapper tDeviceRecordMapper;

    @Autowired
    private ITDevicePlanService itDevicePlanService;

    /**
     * 根据设备的sn号绑定设备
     * @return
     */
    public RpcResult bindDevice(BindParam bindParam ){
        String sn = bindParam.getSn();
        Integer title = bindParam.getTitle();
        Integer mfSet = bindParam.getMfSet();
        MyIJwtAble loginUser = JwtKit.getLoginUser();
        LambdaQueryWrapper<ImsShoppingGoods> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        LambdaQueryWrapper<ImsShoppingGoods> eq = lambdaQueryWrapper.eq(ImsShoppingGoods::getSn, sn);
        List<ImsShoppingGoods> list = iImsShoppingGoodsService.list(eq);
        if(list.isEmpty()){
            return RpcResult.fail("设备不存在");
        }
        ImsShoppingGoods imsShoppingGoods = list.get(0);
        Integer weid = imsShoppingGoods.getWeid();
        if(weid != null && weid>0){
            return RpcResult.fail("该设备已经绑定");
        }
        imsShoppingGoods.setTitle(title);
        imsShoppingGoods.setMfSet(mfSet);
        imsShoppingGoods.setWeid(loginUser.getId());
        Long now = System.currentTimeMillis() / 1000;
        imsShoppingGoods.setBindtime(now.intValue());
        iImsShoppingGoodsService.updateById(imsShoppingGoods);
        return RpcResult.ok();
    }

    public List<Map<String,Object>> listDevice(Integer status){
        if(status == null){
            status = 0;
        }
        MyIJwtAble loginUser = JwtKit.getLoginUser();
        int id = loginUser.getId();
        List<Map<String, Object>> maps = tDeviceRecordMapper.selectCommonSql("SELECT g.mf_set,g.id,g.mac,g.inter_sn, g.title, g.type, g.status, g.sn, g.bindtime, g.online_income, g.region_name, g.sub_region_name, g.description, d.total_coin, d.sig_nal, d.updatetime, d.status as net_state FROM ims_shopping_dev_info d left join ims_shopping_goods g on g.id=d.dev_id where g.weid = "+id+"  ORDER BY g.bindtime ");
        List<Map<String,Object>> list = new ArrayList<>();
        for (Map<String, Object> map : maps) {
            Integer net_state = (Integer) map.get("net_state");
            Long updatetime = Long.valueOf(map.get("updatetime").toString());
            boolean online = devOnlineCheck(net_state, updatetime);
            map.put("online",online);
            Integer $signal = (Integer) map.get("sig_nal");
            map.put("signal",devSignalRank($signal));
            if(status.equals(1)){
                if(!online){
                    continue;
                }
            }
            if(status.equals(2)){
                if(online){
                    continue;
                }
            }
            list.add(map);
        }
        return list;
    }

    /**
     * 根据老系统计算的信号值
     * @param signal
     * @return
     */
    public int devSignalRank(int signal){
        int rank = 1;
        if (signal > 24) {
            rank = 5;
        } else if (signal > 21) {
            rank = 4;
        } else if (signal > 17) {
            rank = 3;
        } else if (signal > 14) {
            rank = 2;
        } else {
            rank = 1;
        }
        return rank;
    }
    /**
     * define('DEV_STAT_UNKNOWN', 0);
     * define('DEV_STAT_OFFLINE', 1);
     * define('DEV_STAT_NORMAL',  2);
     * 默认是1080分钟
     */
    public boolean devOnlineCheck(int status, long updatetimeSeconds) {
        if (status != 2) {
            return false;
        }

        // 将秒转换为毫秒
        long updatetimeMillis = updatetimeSeconds * 1000;

        // 检查updatetime是否小于1080分钟前的时间戳
        if (updatetimeMillis < System.currentTimeMillis() - 1080 * 60 * 1000) {
            return false;
        }

        return true;
    }

    public Map<String,Object> getDeviceInfoByQrcode(String qrcode){
        MyIJwtAble loginUser = JwtKit.getLoginUser();
        int id = loginUser.getId();
        List<Map<String, Object>> maps = tDeviceRecordMapper.selectCommonSql("select * from ims_shopping_goods where sn = '" + qrcode + "'");
        if(maps.isEmpty()){
            return null;
        }
        return maps.get(0);
    }

    @DataSource(DataSourceType.SLAVE)
    public TDevicePlan getPlanInfo(String deviceId, String port, Integer userId) {
        LambdaQueryWrapper<TDevicePlan> objectLambdaQueryWrapper = Wrappers.lambdaQuery();
        objectLambdaQueryWrapper.eq(TDevicePlan::getUserId,userId).eq(TDevicePlan::getStatus,1)
                .eq(TDevicePlan::getDeviceId,deviceId).eq(TDevicePlan::getPort,port).orderByDesc(TDevicePlan::getCreateTime)
                .last("limit 1");
        TDevicePlan one = itDevicePlanService.getOne(objectLambdaQueryWrapper);
        return one;
    }

    /**
     * 修改设备类型
     * @param bindParam
     * @return
     */
    public RpcResult modifyDeviceType(BindParam bindParam) {
        String sn = bindParam.getSn();
        Integer title = bindParam.getTitle();
        Integer mfSet = bindParam.getMfSet();
        MyIJwtAble loginUser = JwtKit.getLoginUser();
        LambdaQueryWrapper<ImsShoppingGoods> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        LambdaQueryWrapper<ImsShoppingGoods> eq = lambdaQueryWrapper.eq(ImsShoppingGoods::getSn, sn);
        List<ImsShoppingGoods> list = iImsShoppingGoodsService.list(eq);
        if(list.isEmpty()){
            return RpcResult.fail("设备不存在");
        }
        ImsShoppingGoods imsShoppingGoods = list.get(0);
        Integer weid = imsShoppingGoods.getWeid();
        if(weid == null){
            weid = 0;
        }
        if(!weid.equals(loginUser.getId())){
            return RpcResult.fail("设备与您未绑定，无权修改");
        }
        imsShoppingGoods.setTitle(title);
        imsShoppingGoods.setMfSet(mfSet);
        iImsShoppingGoodsService.updateById(imsShoppingGoods);
        return RpcResult.ok();
    }

    @DataSource(DataSourceType.SLAVE)
    public Map<String, Object> getDeviceStatusInfo(String deviceId, Integer cmdType) {
        int splitTableNum = SplitDataUtil.getSplitTableNum(deviceId);

        List<Map<String, Object>> maps = tDeviceRecordMapper.selectCommonSql("select * from t_device_record_" + splitTableNum + " where device_id = '" + deviceId + "' and type = " + cmdType + " order by create_time desc limit 1");
        if(maps.isEmpty()){
            return null;
        }else{
            return maps.get(0);
        }

    }
}
